<template>
  <Box class="__search-form-box" :class="[isExpanded ? '__search-form-box-absolute' : '']">
    <el-form :inline="true" :model="form">
      <el-row>
        <!-- 上部：非展开项 -->
        <template v-for="item in formItem" :key="item.name">
          <el-form-item v-if="!item?.hide && !item.expand" :label="item.label + ':'">
            <el-input v-if="item.type === 'input'" v-model="form[item.name]" clearable></el-input>
            <el-select
              v-else-if="item.type === 'select'"
              v-model="form[item.name]"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="option in unref(item.optionConfig?.options) || []"
                :key="option[item.optionConfig?.valueKey || 'value']"
                :label="option[item.optionConfig?.labelKey || 'label']"
                :value="option[item.optionConfig?.valueKey || 'value']"
              ></el-option>
            </el-select>
            <el-date-picker
              v-else-if="item.type === 'datePicker'"
              v-model="form[item.name]"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-bind="item.otherOption"
            ></el-date-picker>
          </el-form-item>
        </template>

        <slot name="formItem" :data="form"></slot>

        <!-- 按钮区域 -->
        <el-form-item v-if="btnsIsShow">
          <el-button :icon="Search" circle @click="search"></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
          <el-button v-if="addFlag" :icon="Plus" type="primary" plain @click="add">新增</el-button>

          <!-- 展开/收缩按钮（仅当有展开项时显示） -->
          <gradient-button
            v-if="hasExpandItems"
            :icon="isExpanded ? ArrowUp : ArrowDown"
            class="expand-btn"
            @click="toggleExpand"
          >
            {{ isExpanded ? '收起' : '展开' }}
          </gradient-button>

          <slot name="btn" :data="form"></slot>
        </el-form-item>
      </el-row>

      <!-- 下部：展开项（仅展开时显示） -->
      <template v-if="hasExpandItems">
        <!-- 分隔线 -->
        <!-- <div class="expand-separator"></div> -->
        <el-row>
          <template v-for="item in formItem" :key="item.name + '-expanded'">
            <el-form-item v-if="!item?.hide && item.expand" :label="item.label + ':'">
              <el-input v-if="item.type === 'input'" v-model="form[item.name]" clearable></el-input>
              <el-select
                v-else-if="item.type === 'select'"
                v-model="form[item.name]"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="option in unref(item.optionConfig?.options) || []"
                  :key="option[item.optionConfig?.valueKey || 'value']"
                  :label="option[item.optionConfig?.labelKey || 'label']"
                  :value="option[item.optionConfig?.valueKey || 'value']"
                ></el-option>
              </el-select>
              <el-date-picker
                v-else-if="item.type === 'datePicker'"
                v-model="form[item.name]"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-bind="item.otherOption"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-row>
      </template>
    </el-form>
  </Box>
</template>

<script lang="ts" setup>
import Box from '@/components/Box/Index.vue'
import { reactive, onMounted, unref, computed, ref } from 'vue'
import type { Ref } from 'vue'
import { Search, Refresh, Plus, ArrowUp, ArrowDown } from '@element-plus/icons-vue'

export interface FormItem {
  name: string
  label: string
  type: 'input' | 'select' | 'datePicker'
  hide?: boolean
  optionConfig?: {
    options: Array<Record<string, any>> | Ref<Array<Record<string, any>>>
    labelKey?: string
    valueKey?: string
  }
  otherOption?: Record<string, any>
  expand?: boolean // 是否为展开项，true:显示在下方，false:显示在上方
}

const props = defineProps({
  formItem: {
    type: Array as () => FormItem[],
    required: true,
    default: () => [],
  },
  formData: {
    type: Object as () => Record<string, any>,
    default: () => ({}),
  },
  btnsIsShow: {
    type: Boolean,
    default: true,
  },
  addFlag: {
    type: Boolean,
    default: false,
  },
})

const emits = defineEmits(['search', 'reset', 'add'])

const form = reactive<Record<string, any>>({})
const isExpanded = ref(false) // 控制展开状态

// 计算是否存在展开项
const hasExpandItems = computed(() => {
  return props.formItem.some((item) => item.expand)
})

onMounted(() => {
  Object.assign(form, props.formData)
})

// 切换展开/收缩状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

const search = () => {
  emits('search', { ...form })
}

const reset = () => {
  const { pageNo, pageSize } = form
  Object.keys(form).forEach((key) => {
    form[key] = ''
  })
  if (pageNo !== undefined && pageSize !== undefined) {
    form.pageNo = pageNo
    form.pageSize = pageSize
  }
  emits('reset', { ...form })
}

const add = () => {
  emits('add')
}
//  :popper-options="{
//       modifiers: [
//           {
//               name: 'flip',
//               options: {
//                   fallbackPlacements: ['bottom'],
//                   allowedAutoPlacements: ['bottom'],
//               }
//           }
//       ]
//   }"
</script>

<style lang="scss" scoped>
.__search-form-box {
  width: 100%;
  height: 65px;
  padding: 16px 16px;

  .expand-btn {
    margin-left: 8px;
  }
}
.__search-form-box-absolute {
  position: relative;
  z-index: 200;
  height: auto;
}
</style>
